//全局混入对象,提供学习时长基本数据,
/**
 * 数据保存在哪？上报策略：
 * 保存到本地storage：读取-解析-写入 循环；二次进入app上报上次保存的文件，成功后删除
 * 全局变量store：如果用户直接杀进程无法保存
 * sqlite：重
 * 实时上传：频繁
 */
import {writeFile} from '@/utils/fileutil';
import {isEmpty} from '@/utils/index';
import {mapState,mapMutations} from 'vuex';
const global = {
	data(){
		return{
			currentPageRoute:'',
			startTimeGlobal:0,
			stayTimeGlobal:0//停留时间，累计计算
		}
	},
	computed:{
		...mapState({
			ascriptionGlobal:(state)=>state.msgStore.ascription,
			ascriptionPage:(state)=>state.msgStore.ascriptionPage,
			currentFileNameGlobal:(state)=>state.msgStore.currentFileName,
			userIdGlobal:(state)=>{
				if(isEmpty(state.user.userData)){
					return ''
				}
				return state.user.userData.id
			}
		})
	},
	onLoad(){
		var pages = getCurrentPages();
		var page = pages[pages.length - 1];
		this.currentPageRoute = page.route;
	},
	onShow(){
		// console.log('======page show',this.currentPageRoute);
		this.startTimeGlobal = new Date().getTime();
	},
	onHide(){
		// console.log('======page hide',this.currentPageRoute);
		this.estimatedTimeGlobal();
	},
	onUnload(){
		// console.log('======page unLoad',this.currentPageRoute);
		this.estimatedTimeGlobal();
		this.setAscriptionPageGlobal({
			ascriptionPage:''
		});
	},
	methods:{
		...mapMutations({
			setTabBarIndex:'msgStore/setTabBarIndex',
			setAscriptionPageGlobal:'msgStore/setAscriptionPage'
		}),
		estimatedTimeGlobal(){
			if(isEmpty(this.currentPageRoute)){
				return;
			}
			if(this.startTimeGlobal!=0){
				const endTime = new Date().getTime();
				this.stayTimeGlobal += (endTime -this.startTimeGlobal);
				const ascription = isEmpty(this.ascriptionPage)?this.ascriptionGlobal:this.ascriptionPage;
				const studyData = {
					"userId":this.userIdGlobal,
					"pagePath":this.currentPageRoute,
					"studyTime":this.stayTimeGlobal,
					"ascription":ascription,
					"startTime":this.startTimeGlobal,
					"endTime":endTime,
					"timestemp":new Date().getTime()
				}
				// console.log('000000写入文件：',studyData);
				//写入文件
				writeFile(this.currentFileNameGlobal,JSON.stringify(studyData)+',');
			}
			this.startTimeGlobal = 0;
			this.stayTimeGlobal = 0;
		}
	}
}
export default global
